package jgl.vajra.management.part.mine.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import jgl.vajra.management.R;
import jgl.vajra.management.databinding.ActivityBusinessCodeBinding;
import jgl.vajra.management.part.mine.contract.BusinessCodeContract;
import jgl.vajra.management.part.mine.viewModel.BusinessCodeViewModel;
import jgl.vajra.management.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.management.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.management.widget.retrofithelper.rxschedulers.RxSchedulersHelper;
import jgl.vajra.management.widget.retrofithelper.rxsubscriber.CommonObserver;
import jgl.vajra.management.widget.utils.FileUtils;
import jgl.vajra.management.widget.utils.MD5Utils;
import jgl.vajra.management.widget.utils.ToastUtils;
import jgl.vajra.management.widget.utils.UIUtils;

@CreateViewModel(BusinessCodeViewModel.class)
public class BusinessCodeActivity extends BaseMVVMActivity<BusinessCodeViewModel, ActivityBusinessCodeBinding> implements BusinessCodeContract.View {
    private Bitmap resourceBitmap;
    private String url = "https://gp-www-cdn.oss-cn-shenzhen.aliyuncs.com/app/wxgzh/gupaonet.jpg?time=";

    @Override
    public int getLayoutId() {
        return R.layout.activity_business_code;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);

        Glide.with(this).asBitmap().load(url)//
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .apply(new RequestOptions().priority(Priority.HIGH))
                        .fitCenter()
                        .dontAnimate())
                .listener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        resourceBitmap = resource;
                        return false;
                    }


                }).into(mBinding.iv);
    }

    @Override
    public void onSaveQrCode() {
        if (resourceBitmap == null) return;
        Observable.create((ObservableOnSubscribe<File>) emitter -> {
            try {
                if (resourceBitmap != null)
                    emitter.onNext(saveImageToGallery(resourceBitmap, url));
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).compose(RxSchedulersHelper.applyIoTransformer()).subscribe(new CommonObserver<File>() {
            @Override
            public void onNext(File o) {
                super.onNext(o);
                ToastUtils.showShort("二维码已保存到相册");
                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(UIUtils.getContext().getContentResolver(),
                            o.getAbsolutePath(), o.getName(), null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 最后通知图库更新
                UIUtils.getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(o)));

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                ToastUtils.showShort("保存失败,请稍后重试");
            }
        });
    }

    //分享名片
    @Override
    public void onShareBusinessCards() {
        ToastUtils.showShort("分享名片");
    }

    /**
     * 保存图片到图库
     *
     * @param bmp
     * @param weChatImgUrl
     */
    public File saveImageToGallery(Bitmap bmp, String weChatImgUrl) {

        File imageFolderFile = FileUtils.getImageFolderFile();
        String fileName = MD5Utils.encode(weChatImgUrl) + ".jpg";
        File file = new File(imageFolderFile, fileName);
        if (file.exists()) {
            return file;
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return file;

    }

}
